﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using Pakxel.Data;
using System.Linq;
using System.Data.Common;
using Telerik.WinControls.UI;

namespace Pakxel.SmartLogistic
{
  public partial class CartaPorteWorkBench : BaseWorkBench
  {
    T021 CartaPorte;
    public CartaPorteWorkBench()
    {
      InitializeComponent();
    }

    void SetupDetalleGrid()
    {
      DetalleGrid.Columns.Add("T023BultosCant", "Cant. Bultos", "T023BultosCant");
      DetalleGrid.Columns.Add("T023BultosClase", "Clase", "T023BultosClase");
      DetalleGrid.Columns.Add("T023Peso", "Peso", "T023Peso");
      DetalleGrid.Columns.Add("T023ValorDeclarado", "Valor Declarado", "T023ValorDeclarado");
      foreach (GridViewDataColumn col in this.DetalleGrid.Columns)
      {
        col.BestFit();
      }
    }

    private void CartaPorteWorkBench_Load(object sender, EventArgs e)
    {
       Flete100.TextBoxElement.TextBoxItem.BackColor = Color.LightYellow;
       Pedimento.TextBoxElement.TextBoxItem.BackColor = Color.LightYellow;
       Fianza.TextBoxElement.TextBoxItem.BackColor = Color.LightYellow;

      base.FilterSelector.Items.Add("Liquidacion");
      ToolStripButton Imprimir = new ToolStripButton("Imprimir");
      Imprimir.Click += new EventHandler(Imprimir_Click);
      WBMenu.Items.Add(Imprimir);

      FilterSelector.Items.Add("Carta Porte");
      DataContext = new Data.MEDataDataContext(WorkBench.ConnectionString);
      tsbSave.Click += new EventHandler(tsbSave_Click);
      tsbNvo.Click += new EventHandler(tsbNvo_Click);
      tsbEdit.Click += new EventHandler(tsbEdit_Click);
      WorkBenchFilter.KeyDown += new KeyEventHandler(WorkBenchFilter_KeyDown);
      SetupDetalleGrid();
      EmptyFields();
    }

    void Imprimir_Click(object sender, EventArgs e)
    {
      if (CartaPorte != null)
      {
        Reportes.CartaPorte CP = new Reportes.CartaPorte();
        Reportes.Reportes Rpt = new Reportes.Reportes { MdiParent = MdiParent };

        #region Scrap
        /*IEnumerable<T005> T05 = (from V in DataContext.T005s where V.T005NoViaje.Equals(Viaje.T005NoViaje) select V).ToList();
                Rpt.Tablas.Add("Pakxel_Data_T005", T05);
                IEnumerable<T006> T06 = (from V in DataContext.T006s where V.T006NoUnidad.Equals(Viaje.T006NoUnidad) select V).ToList();
                Rpt.Tablas.Add("Pakxel_Data_T006", T06);
                IEnumerable<T007> T07 = (from V in DataContext.T007s where V.T007IdRemolque.Equals(Viaje.T007IdRemolque) select V).ToList();
                Rpt.Tablas.Add("Pakxel_Data_T007", T07);
                IEnumerable<T008> T08 = (from V in DataContext.T008s where V.T008IdOrigen.Equals(Viaje.T008IdOrigen) select V).ToList();
                Rpt.Tablas.Add("Pakxel_Data_T008", T08);
                IEnumerable<T008> T08_1 = (from V in DataContext.T008s where V.T008IdOrigen.Equals(Viaje.T008IdDestino) select V).ToList();
                Rpt.Tablas.Add("Pakxel_Data_T008_1", T08_1);
                IEnumerable<T009> T09 = (from V in DataContext.T009s where V.T009IdLinea.Equals(Viaje.T009IdLinea) select V).ToList();
                Rpt.Tablas.Add("Pakxel_Data_T009", T09);
                IEnumerable<T010> T10 = (from V in DataContext.T010s where V.T010NoOperador.Equals(Viaje.T010NoOperador) select V).ToList();
                Rpt.Tablas.Add("Pakxel_Data_T010", T10);
                IEnumerable<T011> T11 = (from V in DataContext.T011s where V.T011NoCliente.Equals(Viaje.T011NoCliente) select V).ToList();
                Rpt.Tablas.Add("Pakxel_Data_T011", T11);
                IEnumerable<T021> T21 = (from V in DataContext.T021s where V.T005NoViaje.Equals(Viaje.T005NoViaje) select V).ToList();
                Rpt.Tablas.Add("Pakxel_Data_T021", T21);
                IEnumerable<T023> T23 = (from V in DataContext.T023s where V.T021NoCartaPorte.Equals(CartaPorte.T021NoCartaPorte) select V).ToList();
                Rpt.Tablas.Add("Pakxel_Data_T023", T23);*/
        #endregion

        //IEnumerable<T005> T05 = (from V in DataContext.T005s where V.T005NoViaje.Equals(Viaje.T005NoViaje) select V).ToList();
        //CP.Database.Tables["Pakxel_Data_T005"].SetDataSource(T05);
        //IEnumerable<T008> T08 = (from V in DataContext.T008s where V.T008IdOrigen.Equals(Viaje.T008IdOrigen) select V).ToList();
        //CP.Database.Tables["Pakxel_Data_T008"].SetDataSource(T08);
        var dsT005 = (from V in DataContext.T005s where V.T005NoViaje.Equals(Viaje.T005NoViaje) select new {V}).ToList();
        CP.Database.Tables["Pakxel_Data_T005"].SetDataSource (dsT005);
        var dsT008 = (from V in DataContext.T008s where V.T008IdOrigen.Equals(Viaje.T008IdOrigen) select new {V}).ToList();
        CP.Database.Tables["Pakxel_Data_T008"].SetDataSource(dsT008);
        #region Pendiente por si se incluyen el destino, cliente y el que paga. (no borrar.)
        //IEnumerable<T008> T08_1 = (from V in DataContext.T008s where V.T008IdOrigen.Equals(Viaje.T008IdDestino) select V).ToList();
        //CP.Database.Tables["Pakxel_Data_T008_1"].SetDataSource(T08_1);
        #endregion

        Rpt.Parametros.Add("Destino", Viaje.T008.T008Nombre);
        Rpt.Parametros.Add("SumValDeclarado", (from S in CartaPorte.T023s select S.T023ValorDeclarado).Sum());
        IEnumerable<T009> T09 = (from V in DataContext.T009s where V.T009IdLinea.Equals(Viaje.T009IdLinea) select V).ToList();
        CP.Database.Tables["Pakxel_Data_T009"].SetDataSource(T09);
        IEnumerable<T010> T10 = (from V in DataContext.T010s where V.T010NoOperador.Equals(Viaje.T010NoOperador) select V).ToList();
        CP.Database.Tables["Pakxel_Data_T010"].SetDataSource(T10);
        IEnumerable<T011> T11 = (from V in DataContext.T011s where V.T011Entity.Equals(Viaje.T011Entity) select V).ToList();
        CP.Database.Tables["Pakxel_Data_T011"].SetDataSource(T11);
        IEnumerable<T021> T21 = (from V in DataContext.T021s where V.T005NoViaje.Equals(Viaje.T005NoViaje) select V).ToList();
        CP.Database.Tables["Pakxel_Data_T021"].SetDataSource(T21);
        IEnumerable<T023> T23 = (from V in DataContext.T023s where V.T021NoCartaPorte.Equals(CartaPorte.T021NoCartaPorte) select V).ToList();
        CP.Subreports["Detalles"].Database.Tables["Pakxel_Data_T023"].SetDataSource(T23);
        Rpt.Reporte = CP;
        Rpt.Show();
      }
    }

    void WorkBenchFilter_KeyDown(object sender, KeyEventArgs e)
    {
      if (e.KeyCode == Keys.Enter)
      {
        var Sel = FilterSelector.SelectedItem.ToString();
        switch (Sel)
        {
          case "NoViaje":
              if (Viaje != null)
              {
                CartaPorte = (from CP in DataContext.T021s where CP.T005NoViaje.Equals(Viaje.T005NoViaje) select CP).SingleOrDefault<T021>();
                ShowCartaPorte(CartaPorte);
              }
              else
              {
                ClearControls(this.Controls);
                EmptyFields();
              }
            break;
          case "Carta Porte":
            if (IsNumeric(WorkBenchFilter.Text))
            {
              CartaPorte = (from CP in DataContext.T021s where CP.T021NoCartaPorte.Equals(WorkBenchFilter.Text) select CP).SingleOrDefault<T021>();
              if (CartaPorte != null)
              {
                ShowViajeInfo(CartaPorte.T005);
                ShowCartaPorte(CartaPorte);
              }
            }
            break;
          default:
            break;
        }
      }
    }

    void EmptyFields()
    {
      NoCartaPorte.Text = string.Empty;
      CartaPorteCte.Text = string.Empty;
      Flete100.Text = string.Empty;
      FleteME.Text = string.Empty;
      Subtotal.Text = string.Empty;
      IVA.Text = string.Empty;
      Retencion.Text = string.Empty;
      Total.Text = string.Empty;
      /// NOTE Se agregan
      Pedimento.Text = string.Empty;
      Fianza.Text = string.Empty;
      FechaCartaPorte.Value = DateTime.Now;
      DetalleGrid.DataSource = null;
      DetalleGrid.AllowAddNewRow = true;
      DetalleGrid.AllowEditRow = true;
      DetalleGrid.AllowDeleteRow = true;
    }

    void ShowCartaPorte(T021 CartaPorte)
    {
      if (CartaPorte != null)
      {
        NoCartaPorte.Text = CartaPorte.T021NoCartaPorte.ToString();
        CartaPorteCte.Text = CartaPorte.T021NoCartaPorteCte;
        Flete100.Text = CartaPorte.T021Flete.ToString();
        FleteME.Text = CartaPorte.T021FleteME.ToString();
        Subtotal.Text = CartaPorte.T021Subtotal.ToString();
        IVA.Text = CartaPorte.T021Iva.ToString();
        Retencion.Text = CartaPorte.T021Retencion.ToString();
        Total.Text = CartaPorte.T021Total.ToString();
        var Facturada = CartaPorte.T021Facturada;
        Pedimento.Text = CartaPorte.T021Pedimento;
        Fianza.Text = CartaPorte.T021Fianza;
        FechaCartaPorte.Value = Convert.ToDateTime(CartaPorte.T021Fecha);
        DetalleGrid.DataSource = CartaPorte.T023s;
        foreach (GridViewDataColumn col in this.DetalleGrid.Columns)
        {
          col.BestFit();
        }
        if (CartaPorte.T021Facturada.Equals('S'))
        {
          DetalleGrid.AllowAddNewRow = false;
          DetalleGrid.AllowEditRow = false;
          DetalleGrid.AllowDeleteRow = false;
        }
        else
        {
          DetalleGrid.AllowAddNewRow = true;
          DetalleGrid.AllowEditRow = true;
          DetalleGrid.AllowDeleteRow = true;
        }
      }
      else
      {
        EmptyFields();
      }
    }

    void tsbEdit_Click(object sender, EventArgs e)
    {
      Flete100.ReadOnly = false;
    }

    void tsbNvo_Click(object sender, EventArgs e)
    {
      ClearControls(this.Controls);
    }

    void tsbSave_Click(object sender, EventArgs e)
    {
      if (Viaje != null)
      {
        if (CartaPorte == null)
        {
          if (DataContext.Connection.State != ConnectionState.Closed)
          {
            DataContext.Connection.Close();
            DataContext.Connection.Open();
          }
          else
            DataContext.Connection.Open();
          using (DbTransaction transaction = DataContext.Connection.BeginTransaction(IsolationLevel.Serializable))
          {
            DataContext.Transaction = transaction;
            try
            {
              T014 Parametros = (from P in DataContext.T014s where P.T014IdParametro.Equals("FOLCP") select P).SingleOrDefault();
              Parametros.T014Val1 = (Convert.ToInt32(Parametros.T014Val1) + 1).ToString();
              DataContext.SubmitChanges();
              CartaPorte = new T021();
              NoCartaPorte.Text = Parametros.T014Val1;
              CartaPorte.T021NoCartaPorte = Convert.ToInt32(Parametros.T014Val1);
              CartaPorte.T021NoCartaPorteCte = CartaPorteCte.Text;
              CartaPorte.T021Flete = Convert.ToDecimal(Flete100.Text);
              CartaPorte.T021FleteME = Convert.ToDecimal(FleteME.Text);
              CartaPorte.T021Subtotal = Convert.ToDecimal(Subtotal.Text);
              CartaPorte.T021Iva = Convert.ToDecimal(IVA.Text);
              CartaPorte.T021Retencion = Convert.ToDecimal(Retencion.Text);
              CartaPorte.T021Total = Convert.ToDecimal(Total.Text);
              CartaPorte.T021Facturada = 'N';
              CartaPorte.T021Fecha = FechaCartaPorte.Value;
              CartaPorte.T021Pedimento = Pedimento.Text;
              CartaPorte.T021Fianza = Fianza.Text;

              foreach (Telerik.WinControls.UI.GridViewRowInfo Row in DetalleGrid.Rows)
              {
                T023 d = new T023();
                d.T021NoCartaPorte = CartaPorte.T021NoCartaPorte;
                d.T023BultosCant = Convert.ToInt32(Row.Cells["T023BultosCant"].Value);
                d.T023BultosClase = Convert.ToString(Row.Cells["T023BultosClase"].Value);
                d.T023Peso = Convert.ToDecimal(Row.Cells["T023Peso"].Value);
                d.T023ValorDeclarado = Convert.ToDecimal(Row.Cells["T023ValorDeclarado"].Value);
                CartaPorte.T023s.Add(d);
              }
              Viaje.T021s.Add(CartaPorte);
              DataContext.SubmitChanges();
              transaction.Commit();
            }
            catch (System.Data.Linq.ChangeConflictException cce)
            {
               MessageBox.Show("Error");
               MainApp.WriteExceptionToLog(cce);
            }
            catch (Exception ex)
            {
              transaction.Rollback();
              MainApp.WriteExceptionToLog(ex);
            }
            finally
            {
              DataContext.Connection.Close();
            }
          }
        }
        else
        {
          if (CartaPorte.T021Facturada.Equals('N'))
          {
             try
             {
                CartaPorte.T021NoCartaPorteCte = CartaPorteCte.Text;
                CartaPorte.T021Flete = Convert.ToDecimal(Flete100.Text);
                CartaPorte.T021FleteME = Convert.ToDecimal(FleteME.Text);
                CartaPorte.T021Subtotal = Convert.ToDecimal(Subtotal.Text);
                CartaPorte.T021Iva = Convert.ToDecimal(IVA.Text);
                CartaPorte.T021Retencion = Convert.ToDecimal(Retencion.Text);
                CartaPorte.T021Total = Convert.ToDecimal(Total.Text);
                CartaPorte.T021Fecha = FechaCartaPorte.Value;
                CartaPorte.T021Pedimento = Pedimento.Text;
                CartaPorte.T021Fianza = Fianza.Text;
                DataContext.SubmitChanges();
             }
             catch (System.Data.Linq.ChangeConflictException cce)
             {
                MessageBox.Show("Error");
                MainApp.WriteExceptionToLog(cce);
             }
             catch (Exception ex)
             {
                MainApp.WriteExceptionToLog(ex);
             }
             finally
             {
                DataContext.Connection.Close();
             }
          }
        }
      }

    }

    private void ImprimirCartaPorte_Click(object sender, EventArgs e)
    {

    }

    private void Flete100_KeyDown(object sender, KeyEventArgs e)
    {
      if (e.KeyCode == Keys.Enter)
      {
        UpdateTotals();
      }
    }

    private void Flete100_Leave(object sender, EventArgs e)
    {
      UpdateTotals();
    }

    void UpdateTotals()
    {
      if (Convert.ToDouble(Flete100.Text) > 0)
      {
        FleteME.Text = (Convert.ToDouble(Flete100.Text) * 0.80).ToString();
        Subtotal.Text = FleteME.Text;
        IVA.Text = (Convert.ToDouble(Subtotal.Text) * 0.16).ToString();
        Retencion.Text = (Convert.ToDouble(Subtotal.Text) * 0.04).ToString();
        Total.Text = (Convert.ToDouble(Subtotal.Text) + Convert.ToDouble(IVA.Text) - Convert.ToDouble(Retencion.Text)).ToString();
      }
    }
  }
}
